package com.atguigu.gmall.product.service.impl;


import com.atguigu.gmall.product.service.TestService;
import org.redisson.api.RLock;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import sun.awt.datatransfer.DataTransferer;

import javax.swing.*;
import java.util.Arrays;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class TestServiceImpl implements TestService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private RedissonClient redissonClient;
    @Override
    public void testLock() {
        //创建锁
        String skuId = "25";
        String locKey = "lock:"+skuId;
        //锁的是每个商品
        RLock lock = redissonClient.getLock(locKey);
        //开始加锁
        lock.lock();
        //业务代码
//        String uuid = UUID.randomUUID().toString();
//        Boolean flag = redisTemplate.opsForValue().setIfAbsent("lock", uuid, 3, TimeUnit.SECONDS);

            //上锁成功 获取数据
            String value = redisTemplate.opsForValue().get("num");
            if (StringUtils.isEmpty(value))return;
            int num = Integer.parseInt(value);
            redisTemplate.opsForValue().set("num",String.valueOf(++num));
            //解锁
        lock.unlock();
//            //定义lua脚本
//            String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
//            //准备执行
//            DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
//            //lua脚本放入DefaultRedisScript对象中
//            redisScript.setScriptText(script);
//            //设置DefaultRedisScript对象的泛型
//            redisScript.setResultType(Long.class);
//            //执行删除
//            redisTemplate.execute(redisScript, Arrays.asList("lock"),uuid);
//            if (redisTemplate.opsForValue().get("lock").equals(uuid))
//                redisTemplate.delete("lock");
    }

    @Override
    public String readLock() {
        RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("readWriteLock");
        RLock rLock = readWriteLock.readLock();
        rLock.lock(10,TimeUnit.SECONDS);
        return redisTemplate.opsForValue().get("msg");


    }

    @Override
    public String writeLock() {
        RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("readWriteLock");
        RLock rLock = readWriteLock.writeLock();
        rLock.lock(10,TimeUnit.SECONDS);
        redisTemplate.opsForValue().set("msg",UUID.randomUUID().toString());
        return "SUCCESS!!!!!!!!!";
    }

}
